package JUC.线程池.池无界;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// 队列0 池无界
public class UseCachedThreadPool {

    public static void main(String[] args) {
        useCached();
    }
    public static void useCached(){
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            // 相当于 new Thread.start
            // execute->Run / submit->Call
            executorService.submit(new Callable<String>() {
                @Override
                public String call() throws Exception{
                    // 为什么 10个 同时start？
                    // 答：因为 异步启动 不干扰主线程 for执行start
                    System.out.println(Thread.currentThread().getName() + " " + finalI + "开始");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " " + finalI + "结束");
                    return "1个体结束";
                }
            });
        }
        executorService.shutdown();
        // System.out.println("---结束"); -> 直接写在这 不行 [ 因为是主线程 上来就执行 ]
        // 卡这 不掉下去
        while (!executorService.isTerminated()){
        }
        System.out.println("--结束");
    }
}
